﻿//***********************************************************************
// Assembly         : NMortgage.UI
// Author           : Mike
// Created          : 04-07-2012
//
// Last Modified By : Mike
// Last Modified On : 04-07-2012
// Description      : 
//
// Copyright        : (c) . All rights reserved.
//***********************************************************************
using System.Globalization;
namespace NMortgage.UI.Model
{
    using System.ComponentModel;
    using System.Linq;

    using Caliburn.Micro;

    using FluentValidation;
    using FluentValidation.Results;
    using System.Diagnostics.CodeAnalysis;

    public abstract class ABaseValidatedType<TEntity, KValidator> : PropertyChangedBase, IValidatable, IDataErrorInfo
        where TEntity : class
        where KValidator : IValidator<TEntity>, new()
    {
        #region Properties

        public string Error
        {
            get { return ValidationHelper.GetError(SelfValidate()); }
        }

        public bool IsValid
        {
            get { return SelfValidate().IsValid; }
        }

        #endregion Properties

        #region Indexers

        public string this[string columnName]
        {
            get
            {
                var validationResults = SelfValidate();
                if (validationResults == null) return string.Empty;
                var columnResults = validationResults.Errors.FirstOrDefault<ValidationFailure>(x => string.Compare(x.PropertyName, columnName, true, CultureInfo.CurrentCulture) == 0);
                return columnResults != null ? columnResults.ErrorMessage : string.Empty;
            }
        }

        #endregion Indexers

        #region Methods

        public ValidationResult SelfValidate()
        {
            TEntity self = this as TEntity;
            return ValidationHelper.Validate<TEntity, KValidator>(self);
        }

        #endregion Methods
    }
}